<template>
  <el-tabs type="border-card">
    <el-tab-pane label="密钥申请">

      <el-form ref="ruleFormRef" :model="keyForm" label-width="150px" class="form-key" :rules="keyRule">
        <el-form-item label="请选择申请参数" prop="select">
          <el-select v-model="keyForm.select" placeholder="请选择">
            <el-option label="身份证号码" value="id_card_num" />
            <el-option label="手机号码" value="mobile_num" />
            <el-option label="邮箱地址" value="email_addr" />
            <el-option label="QQ号码" value="qq_num" />
            <el-option label="家庭住址" value="family_addr" />
            <el-option label="社保卡号" value="insurance_card_num" />
          </el-select>
        </el-form-item>
        <el-form-item label="请输入参数（公钥）" prop="PubKey">
          <el-input v-model="keyForm.PubKey" class="input-key"/>
        </el-form-item>
        <el-form-item label="分发方式" prop="distribution">
          <el-select v-model="keyForm.distribution" placeholder="请选择">
            <el-option label="邮件分发" value="1" />
            <el-option label="屏幕显示" value="3" />
            <el-option label="打印留存" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="keyForm.distribution == 'email'" label="请输入邮箱" prop="email">
          <el-input v-model="keyForm.email" class="input-key" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit(ruleFormRef)" :disabled="store.getPubKey !== ''">提交申请</el-button>
        </el-form-item>
      </el-form>

      <el-dialog v-model="dialogFormVisible" title="验证身份">
        <el-form :model="testVerify">
          <el-form-item :label="labelTest + testVerify[0]" :label-width="formLabelWidth">
            <el-input v-model="testInfo.first" autocomplete="off" />
          </el-form-item>
          <el-form-item :label="labelTest + testVerify[1]" :label-width="formLabelWidth">
            <el-input v-model="testInfo.second" autocomplete="off" />
          </el-form-item>
          <div class="falseMark" v-if="falseMark > 0">
            <span>您还可以尝试{{3-falseMark}}次</span>
          </div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="submitPub">提交</el-button>
            <el-button type="primary" @click="confirm">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </el-tab-pane>
    <el-tab-pane label="密钥分发">
      <div class="font-pub" v-if="store.getSendType === '3'">
        <!--        <span>您当前的公钥为：{{PubKey}}</span><br>-->
        <div style="margin-top: 8px;width: 400px">您当前的私钥为：</div>
        <el-input disabled  v-model="store.getPriKey" style="margin-top: 10px" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }" :placeholder="store.getPubKey" />
      </div>
      <div class="font-pub" v-if="store.getSendType === '1'">
        <el-result
            icon="success"
            title="成功"
            sub-title="已发送至您的邮箱，请查收邮件"
        ></el-result>
      </div>
      <div class="font-pub" v-if="store.getSendType === '2'">
        <el-result
            icon="success"
            title="成功"
            sub-title="已成功打印"
        ></el-result>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup lang="ts">

import {reactive, ref} from "vue";
import loginInfo from "@/stores/loginInfo";
import {ElMessage} from "element-plus";
import type { FormInstance, FormRules } from 'element-plus'
import axios from "axios";

const ruleFormRef = ref<FormInstance>()
const store = loginInfo()
const PubKey = store.getPubKey
interface  keyFormInfo {
  select: string,
  distribution: string,
  email: string,
  PubKey: string,
}
const keyForm = reactive({
  select: '',
  distribution: '',
  email: '',
  PubKey: '',
})
const testVerify= reactive<string[]>([])
const testInfo = reactive({
  first:'',
  second:''
})
const realTestInfo = reactive<string[]>([])
const createChineseName = () => {
  for (let [key, value] of Object.entries(testMap.value)) {
    if (testMap.value.hasOwnProperty(key)) { // 确保key是obj自身的属性，而非继承来的
      if (key === "id_card_num") {
        realTestInfo.push(value);
        testVerify.push('身份证号码')
      } else if (key === "mobile_num") {
        realTestInfo.push(value);
        testVerify.push('手机号码')
      } else if (key === "email_addr") {
        realTestInfo.push(value);
        testVerify.push('邮箱地址')
      } else if (key === "qq_num") {
        realTestInfo.push(value);
        testVerify.push('QQ号码')
      } else if (key === "family_addr") {
        realTestInfo.push(value);
        testVerify.push('家庭住址')
      } else if (key === "insurance_card_num") {
        realTestInfo.push(value);
        testVerify.push('社保卡号')
      }
    }
  }
}
const labelTest =  '请输入'
const dialogFormVisible  = ref(false)
const formLabelWidth = '140px'

const testMap = ref({})
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogFormVisible.value= true
      axios.get('http://localhost:8082/requestKey/userTest/'+store.getId).then(res => {
        if (res){
          testMap.value = res.data.data
          console.log(testMap.value)
          createChineseName()
          console.log(testVerify)
        }
      })
    } else {
      console.log('缺少输入')
      return
    }
  })
}
const confirm  = () => {
  dialogFormVisible.value= false
  ElMessage({
    message: '取消验证',
    type: 'error',
  })
  testInfo.first = ''
  testInfo.second = ''
  falseMark.value = 0
}
const keyRule = reactive<FormRules<keyFormInfo>>({
  select:[
    {required: true, message: '请选择申请参数', trigger: 'change'},
  ],
  PubKey:[
    {required: true, message: '请输入申请参数', trigger: 'blur'}
  ],
  distribution:[
    {required: true, message: '请输入邮箱', trigger: 'blur'}
  ],
  email:[
    {required: true, message: '请输入邮箱', trigger: 'blur'}
  ]
})
const falseMark = ref(0)
const submitPub = () => {
  if(testInfo.first === realTestInfo[0] && testInfo.second === realTestInfo[1]){
    ElMessage({
      message: '验证成功',
      type: 'success',
    })
    testVerify.pop()
    testVerify.pop()
    dialogFormVisible.value= false
    axios.get('http://localhost:8082/requestKey/PriKey',{
      params: {
        PubKey: keyForm.PubKey,
        user_id : store.getId,
        requestPara : keyForm.select,
        sendType : keyForm.distribution
      }
    }).then(
            res => {
              store.setPubKey(keyForm.PubKey)
              store.setPriKey(res.data.data)
              store.setSendType(keyForm.distribution)
              location. reload()
            }

        ).catch(e =>{
      console.log(e)
    })
    axios.get('http://localhost:8082/requestKey/updateUser',{
      params:{
        user_id : store.getId,
        pub_key : store.getPubKey
      }
    }).then(
        res => {
          console.log(res)
        }
    )
  }else {
    falseMark.value++
    if (falseMark.value === 3){
      ElMessage({
        message: '退出系统',
        type: 'error',
      })
      window.location.href = 'http://127.0.0.1:5173/#/login'
    }else {
      ElMessage({
        message: '验证失败',
        type: 'warning',
      })
    }

  }
}
</script>

<style scoped>
.font-pub{
  margin-left: 10px;
  margin-top: 20px;
}
.form-key{
  margin-top: 30px;
}
.input-key{
  width: 300px;
}
.falseMark{
  margin-left: 20px;
  font-size: medium;
  color: red;
}
</style>